package com.bah.tract.client.ui.menu;

import java.awt.CheckboxMenuItem;
import java.awt.Image;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.prefs.Preferences;

import javax.swing.JDialog;
import javax.swing.JOptionPane;

import com.bah.tract.client.Main;
import com.google.inject.Inject;
import com.google.inject.name.Named;

public class TaskReminderMenuItem extends CheckboxMenuItem {

	private static final String TASK_REMINDER = "TaskReminder";

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private boolean remind;

	private final Preferences prefs;

	private final ScheduledExecutorService mExecutorService;

	private ScheduledFuture<?> future;

	private JDialog reminderDialog;

	@Inject
	TaskReminderMenuItem(@Named("defaultImage") final Image image,
			final ScheduledExecutorService executorService) {
		super("Task Reminder");
		JOptionPane reminderPane = new JOptionPane("Please confirm your TRACT tasks.",
				JOptionPane.PLAIN_MESSAGE);
		reminderDialog = reminderPane.createDialog("TRACT");
		reminderDialog.setIconImage(image);
		mExecutorService = executorService;
		prefs = Preferences.userNodeForPackage(Main.class);
		remind = prefs.getBoolean(TASK_REMINDER, true);
		if (remind) {
			scheduleReminder();
		}
		setState(remind);
		addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(final ItemEvent e) {
				remind = !remind;
				if (remind) {
					scheduleReminder();
				} else {
					future.cancel(false);
				}
				prefs.putBoolean(TASK_REMINDER, remind);
			}
		});
	}

	private void scheduleReminder() {
		final int reminderInterval = prefs.getInt("reminder", 15);
		future = mExecutorService.scheduleAtFixedRate(new ReminderMessage(),
				reminderInterval, reminderInterval, TimeUnit.MINUTES);
	}

	private class ReminderMessage implements Runnable {

		@Override
		public void run() {
			// Suppress multiple reminders
			future.cancel(false);
			reminderDialog.setVisible(true);
			// After they hit OK resume the reminders with a fresh timer
			scheduleReminder();
		}

	}

}
